import 'dart:convert';
import 'package:flutter/material.dart';

import 'package:flutter_note/note/base.dart';
import 'package:flutter_note/note/bean.dart';
import 'package:flutter_note/note/const.dart';
import 'package:flutter_note/note/manager.dart';
import 'package:flutter_note/note/page_book_add.dart';
import 'package:flutter_note/note/page_book_note.dart';
import 'package:flutter_note/note/utils.dart';
import 'package:flutter_note/note/widgets.dart';

class BookPage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return _BookPageState();
  }
}

class _BookPageState extends BaseState<BookPage> {
  List<Book> _bookList = BookManager.getInstance().getBookList();

  @override
  void initState() {
    super.initState();
    _initData();
  }

  void _initData() async {
    if (EmptyUtils.isEmpty(_bookList)) {
      //如果列表是空的,先从服务器拉取,如果有内容直接显示
      await BookManager.getInstance().loadData(); //必须要await,不然拉取了不能更新
    }
    setState(() {
      _bookList = BookManager.getInstance().getBookList();
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      key: scaffoldkey,
      backgroundColor: color.bg_page,
      body: Container(
        child: GridView.count(
          crossAxisCount: 2,
          crossAxisSpacing: dim.x10,
          children: buildList(),
        ),
      ),
    );
  }

  List<Widget> buildList() {
    if (EmptyUtils.isEmpty(_bookList)) {
      return List.generate(
        1,
        (index) {
          return buildAddItem();
        },
      );
    } else {
      return List.generate(
        _bookList.length + 1,
        (index) {
          if (index == 0) {
            return buildAddItem();
          } else {
            return buildBookItem(_bookList[index - 1]);
          }
        },
      );
    }
  }

  Widget buildBookItem(Book book) {
    return Container(
      padding: EdgeInsets.only(
          left: dim.x20, right: dim.x20, top: dim.x10, bottom: dim.x10),
      child: RaisedButton(
        shape: BorderDirectional(),
        color: color.white,
        padding: EdgeInsets.all(0.0),
        elevation: dim.x2,
        highlightElevation: dim.x1,
        onPressed: () async {
          goBookNotePage(book);
        },
        child: Column(
          children: <Widget>[
            Expanded(
              flex: 1,
              child: Container(
                color: color.a6_grey,
                child: Center(
                  child: ClipImageView(
                      book.pic, dim.x60, dim.x60, Const.IMG_SIZE_NOTE),
                ),
              ),
            ),
            Expanded(
              flex: 1,
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                crossAxisAlignment: CrossAxisAlignment.center,
                children: <Widget>[
                  Text("${book.title}",
                      style: TextStyle(
                          fontSize: dim.t16,
                          color: color.txt3,
                          fontWeight: FontWeight.bold)),
                  Space(Const.SPACE_TOP, size: dim.x5),
                  Text(DateUtils.msToYMD(book.bTime)),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget buildAddItem() {
    return Container(
      padding: EdgeInsets.only(
          left: dim.x20, right: dim.x20, top: dim.x10, bottom: dim.x10),
      child: RaisedButton(
        shape: BorderDirectional(),
        color: color.white,
        padding: EdgeInsets.all(0.0),
        elevation: dim.x2,
        highlightElevation: dim.x1,
        onPressed: () {
          goAddBookPage();
        },
        child: Container(
          color: color.a6_grey,
          child: Center(
            child: Icon(
              Icons.add,
              size: dim.x30,
            ),
          ),
        ),
      ),
    );
  }

  goAddBookPage() async {
    var reply = await startPageForResult(AddBookPage());
    if (reply is Reply) {
      var book = Book.fromJson(json.decode(reply.data));
      print(book.toString());
      showMessage(reply.msg);
      await BookManager.getInstance().loadData(); //必须要await,不然拉取了不能更新
      setState(() {
        _bookList = BookManager.getInstance().getBookList();
      });
    }
  }

  goBookNotePage(book) async {
    var bookNoteManager = BookNoteManager.getInstance();
    if (bookNoteManager.getCurrentBook() != book) {
      bookNoteManager.setCurrentBook(book); //和之前的bid不一样的时候需要重新赋值
      bookNoteManager.getNoteList().clear(); //清掉之前的数据
    }
    startPage(BookNotePage());
  }
}
